﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FourSquare.Domain.Entities;
using FourSquare.Core;
using FourSquareSQH.Web.Models;
using System.Net.Mail;
using System.Net;
using System.Text;

namespace FourSquareSQH.Web.Controllers
{
    public class FourSquareController : Controller
    {
        private FourSquareCore core;
        private string[] colors = new string[] { "black", "brown", "green","purple","yellow","blue","gray","orange","red","white" };       
        private string mapMarker = "";
        List<Coordinates> _coordinates = new List<Coordinates>();

        private class Coordinates
        {
            public float Latitude { get; set; }
            public float Longitude { get; set; }
        }

        public FourSquareController()
        {
            core = new FourSquareCore("", "", "ZTEHHIIFIAL40H4RMHDZKXBYTNSLNMVOTDEVXCDEESLBINOQ");
        }

        private string GetPhotoUrl(string venueId)
        {
            string photoUrl = "";
            FourSquareEntityItems<Photo> photo = core.GetVenuesPhotos(venueId);
            if (photo.Count > 0)
                photoUrl = String.Format("{0}200x200{1}", photo.Items[0].Prefix, photo.Items[0].Suffix);

            return photoUrl;
        }

        private void CreateMarkers(float lat, float lng)
        {
            mapMarker = mapMarker + String.Format("markers=color:{0}%7Clabel:A%7C{1},{2}&", GenerateRandomColor(), lat, lng);
            _coordinates.Add(new Coordinates { Latitude = lat, Longitude = lng });
        }

        private string GenerateRandomColor()
        {
            Random random = new Random();
            int num = random.Next(colors.Length);
            return colors[num];
        }

        private List<VenueViewModel> GetVenues(string near, int limit, decimal radius ,string query)
        {
            List<VenueViewModel> viewModel = new List<VenueViewModel>();
            Explore venues = core.GetRecommendedAndPopularVenues(near, null, null, limit, radius, null, query, null, null);
            if (venues.Groups.Count > 0)
            {
                foreach(var item in venues.Groups[0].Items)
                {
                    VenueViewModel v = new VenueViewModel()
                    {
                        Name = item.Venue.Name,
                        Description = item.Venue.Description,
                        Id = item.Venue.Id,
                        Tips = item.Tips,
                        Lat = item.Venue.Location.Lat,
                        Lng = item.Venue.Location.Lng,
                        CheckInCount = item.Venue.Stats.CheckInsCount,
                        Category = item.Venue.Categories != null ? item.Venue.Categories[0].Name : "",
                        PhotoURL = GetPhotoUrl(item.Venue.Id)
                    };

                    viewModel.Add(v);
                    CreateMarkers(item.Venue.Location.Lat, item.Venue.Location.Lng);
                }
            }

            return viewModel;
        }

        public ActionResult Index(string near)
        {
            List<VenueViewModel> viewModel = new List<VenueViewModel>();

            List<VenueViewModel> foodVenues = GetVenues(near, 3, 1000, "food");
            List<VenueViewModel> coffeeVenues = GetVenues(near, 1, 1000, "coffee");
            List<VenueViewModel> parkVenues = GetVenues(near, 3, 1000, "park");
            List<VenueViewModel> recreationVenues = GetVenues(near, 1, 1000, "recreation");

            if (foodVenues.Count == 0 && coffeeVenues.Count == 0 && parkVenues.Count == 0 && recreationVenues.Count == 0)
            {
                TempData["Message"] = "We didn't find anything interesting for you to do in '" + near +"'. Try another place.";
                return RedirectToAction("Index", "Home");
            }
            else
            {
                foodVenues[0].Time = "9am to 10am: Early in the morning, grab your breakfast at..";
                foodVenues[0].Position = 1;

                foodVenues[1].Time = "12noon to 1pm: Take your lunch in..";
                foodVenues[1].Position = 3;

                foodVenues[2].Time = "7pm to 8pm: End the day, take your dinner at..";
                foodVenues[2].Position = 8;

                coffeeVenues[0].Time = "3pm to 4pm: Stop for an afternoon break, sip a cup of coffee at..";
                coffeeVenues[0].Position = 5;

                recreationVenues[0].Time = "1pm to 3pm: Walk over to, you're bound to have fun there";
                recreationVenues[0].Position = 4;

                parkVenues[0].Time = "10am to 12noon: After getting breakfast, take a relaxing walk, breathe fresh air at..";
                parkVenues[0].Position = 2;

                parkVenues[1].Time = "4pm to 5pm: Bring out your cameras and stroll around..";
                parkVenues[1].Position = 6;

                parkVenues[2].Time = "5pm to 6pm: The night draws near, appreciate the sunset at..";
                parkVenues[2].Position = 7;
                
                viewModel.AddRange(foodVenues);
                viewModel.AddRange(parkVenues);
                viewModel.AddRange(recreationVenues);
                viewModel.AddRange(coffeeVenues);

                List<VenueViewModel> fordisplay = viewModel.OrderBy(x => x.Position).ToList();
                ConstructMap();
                return View(fordisplay);
            }
        }

        [HttpPost]
        public ActionResult Index(FormCollection collection, string near)
        {
            List<VenueViewModel> viewModel = new List<VenueViewModel>();

            List<VenueViewModel> foodVenues = GetVenues(near, 3, 1000, "food");
            List<VenueViewModel> coffeeVenues = GetVenues(near, 1, 1000, "coffee");
            List<VenueViewModel> parkVenues = GetVenues(near, 3, 1000, "park");
            List<VenueViewModel> recreationVenues = GetVenues(near, 1, 1000, "recreation");

            foodVenues[0].Time = "9am to 10am: Early in the morning, grab your breakfast at..";
            foodVenues[0].Position = 1;

            foodVenues[1].Time = "12noon to 1pm: Take your lunch in..";
            foodVenues[1].Position = 3;

            foodVenues[2].Time = "7pm to 8pm: End the day, take your dinner at..";
            foodVenues[2].Position = 8;

            coffeeVenues[0].Time = "3pm to 4pm: Stop for an afternoon break, sip a cup of coffee at..";
            coffeeVenues[0].Position = 5;

            recreationVenues[0].Time = "1pm to 3pm: Walk over to, you're bound to have fun there";
            recreationVenues[0].Position = 4;

            parkVenues[0].Time = "10am to 12noon: After getting breakfast, take a relaxing walk, breathe fresh air at..";
            parkVenues[0].Position = 2;

            parkVenues[1].Time = "4pm to 5pm: Bring out your cameras and stroll around..";
            parkVenues[1].Position = 6;

            parkVenues[2].Time = "5pm to 6pm: The night draws near, appreciate the sunset at..";
            parkVenues[2].Position = 7;

            viewModel.AddRange(foodVenues);
            viewModel.AddRange(parkVenues);
            viewModel.AddRange(recreationVenues);
            viewModel.AddRange(coffeeVenues);

            List<VenueViewModel> fordisplay = viewModel.OrderBy(x => x.Position).ToList();

            StringBuilder message = new StringBuilder();

            foreach (VenueViewModel venue in fordisplay)
            {
                message.AppendLine(venue.Time + "<br/>" + venue.Name + "<br/>");
                message.AppendLine(venue.Category + "<br/><br/>");
            }            

            try
            {
                var fromAddress = new MailAddress("ace.subido@gmail.com", "One Day Trip");
                var toAddress = new MailAddress(collection["emailField"], collection["emailField"]);
                const string fromPassword = "$Rvert23low&*freak0>";
                const string subject = "Your Day Trip | Itinerary";

                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = Convert.ToInt32(587),
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };

                using (var mailMessage =
                        new MailMessage(fromAddress, toAddress)
                        {
                            IsBodyHtml = true,
                            Subject = subject,
                            Body = message.ToString()
                        })
                {
                    smtp.Send(mailMessage);
                }

                return View(viewModel);
            }
            catch (Exception ex)
            {
                return View(viewModel);
            }        
        }

        public ActionResult ViewMap()
        {
            return View();
        }

        private void ConstructMap()
        {
            //find the largest longitude
            float longitude = _coordinates.Max(e => e.Longitude);
            float latitude = _coordinates.Max(e => e.Latitude);

            var map2 = String.Format("http://maps.googleapis.com/maps/api/staticmap?center={0},{1}&zoom=12&size=800x800&sensor=false&maptype=roadmap&{2}", latitude, longitude, mapMarker);
            ViewBag.Map = map2;
        }
    }
}
